package com.zx.tradeclient.ctrl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.zx.base.ctrl.BaseActivity;
import com.zx.base.http.HttpUtils;
import com.zx.base.http.HttpUtils.CallBack;
import com.zx.base.util.ActivityTaskManager;
import com.zx.base.widget.LoadMoreListView;
import com.zx.base.widget.LoadMoreListView.OnLoadMoreListener;
import com.zx.base.widget.LoadMoreListViewWithProgress;
import com.zx.tradeclient.R;
import com.zx.tradeclient.adapter.ProductPageAdapter;
import com.zx.tradeclient.app.TradeApp;
import com.zx.tradeclient.ctrl.index4.ProductInfoActivity;
import com.zx.tradeclient.entity.ProductItemInfo;

public class SearchActivity extends BaseActivity implements OnClickListener {
	/** Called when the activity is first created. */

	private ImageButton search_button;
	// private Spinner search_spinner;
	private EditText search_edit;

	// private String[] arr = new String[] {"新闻","供求","产品","企业"};

	private int mSelect = 2;

	private TradeApp app;

	private ProductPageAdapter adapter3;
	private ArrayList<ProductItemInfo> info3 = new ArrayList<ProductItemInfo>();
	/*
	 * private CompanyPageAdapter adapter4; private ArrayList<PageInfo> info4 =
	 * new ArrayList<PageInfo>();
	 */

	private LoadMoreListViewWithProgress viewWhitProgress;
	private LoadMoreListView listView;
	private int currentPage;
	private int totalPage;
	private int perPageCount = 14;
	private LinearLayout linear;

	private boolean is_init = false;
	
	private String mIndex = "0";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_activity);

		if (!(ActivityTaskManager.getInstance().containsName("SearchActivity"))) {
			ActivityTaskManager.getInstance().putActivity("SearchActivity",
					this);
		}

		init();
	}

	private void init() {

		app = (TradeApp) getMyApplication();
		
		mIndex = getIntent().getStringExtra("index");

		setHeader(0);

		header_left.setOnClickListener(this);

		search_button = (ImageButton) findViewById(R.id.search_button);
		search_button.setOnClickListener(this);

		/*
		 * search_spinner = (Spinner) findViewById(R.id.search_spinner);
		 * ArrayAdapter<String> spinner_adapter=new ArrayAdapter<String>(this,
		 * android.R.layout.simple_spinner_item, arr);
		 * spinner_adapter.setDropDownViewResource
		 * (android.R.layout.simple_spinner_dropdown_item);
		 * search_spinner.setAdapter(spinner_adapter);
		 * search_spinner.setOnItemSelectedListener(m_SpinnerListener);
		 * search_spinner.setVisibility(View.VISIBLE);
		 * search_spinner.setSelection(mSelect);
		 */

		search_edit = (EditText) findViewById(R.id.search_edit);

		linear = (LinearLayout) findViewById(R.id.search_text_linear);

	}

	private void loadData() {

		adapter3 = new ProductPageAdapter(SearchActivity.this, info3,
				app.imageLoader);

		viewWhitProgress = new LoadMoreListViewWithProgress(this);
		listView = viewWhitProgress.getListView();
		listView.setDivider(getResources().getDrawable(R.drawable.divider));
		listView.setSelector(getResources().getDrawable(
				R.drawable.list_item_colorexchange));
		listView.setDividerHeight(2);
		listView.setAdapter(adapter3);

		/*
		 * switch (mSelect) { case 1:
		 * 
		 * break;
		 * 
		 * case 2: break; case 3: adapter3 = new
		 * ProductPageAdapter(SearchActivity.this, info3, app.imageLoader);
		 * listView.setAdapter(adapter3); break; case 4: adapter4 = new
		 * CompanyPageAdapter(SearchActivity.this, info4, app.imageLoader);
		 * listView.setAdapter(adapter4); break;
		 * 
		 * default: break; }
		 */

		listView.setOnLoadMoreListener(new OnLoadMoreListener() {

			@Override
			public void onLoadMore() {
				loadDataTask();
			}
		});
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (((TradeApp) getApplicationContext()).isNetWorkConnection) {
					Intent intent3 = new Intent(SearchActivity.this,
							ProductInfoActivity.class);
					intent3.putExtra("productID", info3.get(position)
							.getPage_id());
					startActivity(intent3);

				} else {
					Toast toast2 = Toast.makeText(SearchActivity.this,
							"网络连接断开，请检查网络", Toast.LENGTH_SHORT);
					toast2.setGravity(Gravity.CENTER, 0, 0);
					toast2.show();
				}

			}
		});

		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		int height = metric.heightPixels;
		float px = 64 * (metric.densityDpi / 160f);
		perPageCount = (int) Math.ceil(height / px);

		linear.addView(viewWhitProgress);

	}

	/*
	 * private Spinner.OnItemSelectedListener m_SpinnerListener=new
	 * Spinner.OnItemSelectedListener() { public void
	 * onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { //
	 * TODO Auto-generated method stub //arg0.setVisibility(View.VISIBLE);
	 * 
	 * }
	 * 
	 * public void onNothingSelected(AdapterView<?> arg0) { // TODO
	 * Auto-generated method stub
	 * 
	 * } };
	 */

	private void loadDataTask() {

		currentPage = currentPage + 1;
		Map<String, String> map = new HashMap<String, String>();
		map.put("act", "productList");
		map.put("productName", search_edit.getText().toString());
		map.put("currentPage", String.valueOf(currentPage));
		map.put("rowCountPerPage", perPageCount + "");
		HttpUtils.post(map, new CallBack() {

			@Override
			public void onSuccess(JSONObject response) {

				try {
					String succeed = response.getString("succeed");
					if (succeed.equals("000")) {
						String data = response.getString("dataList");

						JSONArray list = new JSONArray(data);

						for (int i = 0; i < list.length(); i++) {
							ProductItemInfo info = new ProductItemInfo();
							JSONObject log = list.getJSONObject(i);
							info.setPage_id(log.getString("id"));
							info.setPage_icon(log.getString("photo"));
							info.setPage_name(log.getString("name"));
							info.setPage_price(log.getString("price"));
							info.setPage_categ(log.getString("productType"));
							info.setPage_comname(log.getString("companyName"));
							info.setPage_area(log.getString("city"));

							info3.add(info);
						}
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

				// We need notify the adapter that the data have been changed
				adapter3.notifyDataSetChanged();
				viewWhitProgress.show();

				if (0 == info3.size()) {
					Toast toast2 = Toast.makeText(SearchActivity.this,
							"没有搜索到数据", Toast.LENGTH_SHORT);
					toast2.setGravity(Gravity.CENTER, 0, 0);
					toast2.show();
				}

			}

			@Override
			public void onFailure(Throwable e) {
				// TODO Auto-generated method stub

			}
		});

	}

	public void onClick(View v) {
		if (v == search_button) {
			if (is_init) {
				linear.removeAllViews();
				info3.clear();
				currentPage = 0;
				totalPage = 0;
				perPageCount = 10 ;
			} else {
				is_init = true;
				
			}
			
			loadData();
			loadDataTask();

		} else if (v == header_left) {
			back();
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			back();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private void back(){
		if(mIndex.equals("1")){
			SearchActivity.this.finish();
		}else{
			goback();
		}
	}

}